package cn.client.ui.view.main.dynamic

import android.widget.Toast
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.lazy.staggeredgrid.LazyVerticalStaggeredGrid
import androidx.compose.foundation.lazy.staggeredgrid.StaggeredGridCells
import androidx.compose.foundation.lazy.staggeredgrid.items
import androidx.compose.foundation.lazy.staggeredgrid.rememberLazyStaggeredGridState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.PopupProperties
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import cn.client.R
import cn.client.data.remoteData.bean.DateUtils
import cn.client.data.remoteData.bean.DynamicData
import cn.client.data.remoteData.bean.PageSelectByUid
import cn.client.data.userStateManager
import coil.compose.AsyncImage
import kotlinx.coroutines.launch


/**
 * 动态页面区域
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DynamicScreen(
    navController: NavController,
    onClickDynamicInfo: (Int, Int) -> Unit = { _, _ -> },
    onClickEditDynamic: (Int) -> Unit = {},
    onClickSubject: (Int) -> Unit = {},
    viewModel: DynamicViewModel = hiltViewModel()
) {
    // 使用 collectAsState 来观察 ViewModel 中的 dynamicDataList 状态
    val dynamicDataListState = viewModel.dynamicDataList.collectAsState(initial = emptyList())
    val dynamicDataList = dynamicDataListState.value

    /* 分页查询 */
    val pageNo: Int = 1
    val pageSize: Int = 10
    val coroutineScope = rememberCoroutineScope()
    val context = LocalContext.current

    val listState = rememberLazyStaggeredGridState()

    // 使用 collectAsState 观察 userId 的变化
//    val userIdState = viewModel.userId.collectAsState(initial = -1)
//    val userId = userIdState.value
    val userIdState = userStateManager.userId.collectAsState(initial = -1)
    val userId = userIdState.value

    // 直接修改为在本地拿到userId缓存发送请求

    data class DropdownItem(val title: String, val id: Int)
    val dropdownList = listOf(
        DropdownItem("分享动态", 1),
        DropdownItem("话题", 2)
    )
    var expanded by remember { mutableStateOf(false) }

    val pageSelectByUid = PageSelectByUid(uid = userId, pageNo = pageNo, pageSize = pageSize)

    if (userId == -1){
        viewModel.dispatch(DynamicViewModel.PageIntent.GetUser("获取本地用户缓存"))
    } else {
        viewModel.dispatch(DynamicViewModel.PageIntent.GetDynamicList(pageSelectByUid))
    }


    LaunchedEffect(Unit) {
        viewModel.pageEvents.collect { it->
            when(it){
                is DynamicViewModel.PageEvent.UserRes -> {
                    viewModel.dispatch(DynamicViewModel.PageIntent.GetDynamicList(pageSelectByUid))
                }
                is DynamicViewModel.PageEvent.GetErr -> {
                    Toast.makeText(context, "提示：${it.msg}", Toast.LENGTH_SHORT).show()
//                    navController.navigate(AppStart.route) {
//                        popUpTo(Overview.route) {
//                            inclusive = true
//                        }
//                        launchSingleTop = true
//                    }
                }
                else -> {}
            }
        }
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.White)
    ) {
        /* 顶部导航栏 */
        TopAppBar(
            colors = TopAppBarDefaults.topAppBarColors(
                containerColor = MaterialTheme.colorScheme.primaryContainer,
                titleContentColor = MaterialTheme.colorScheme.primary),
            title = { Text("动态广场") },
            /* 左边按钮 */
            navigationIcon = {
                Icon( painter = painterResource(R.drawable.ic_share_one), null)
//                IconButton( onClick = {   } ) { Icon( painter = painterResource(R.drawable.ic_share_one), null) }
                             },
            /* 右边按钮（可以是多个） */
            actions = {
                IconButton(onClick = { expanded =! expanded }
                ) { Icon(Icons.Filled.MoreVert, null)
                    /* 下拉框 */
                    DropdownMenu(
                        expanded = expanded,
                        onDismissRequest = { expanded = !expanded }, // 当下拉菜单展开/关闭时更新状态
                        modifier = Modifier.wrapContentSize(),
                        properties = PopupProperties(
                            focusable = true,
                            dismissOnBackPress = false,
                            dismissOnClickOutside = true
                        )
                    ) {
                        dropdownList.forEach { dropItem ->
                            DropdownMenuItem(
                                { Text(text = dropItem.title) },
                                onClick = {
                                    expanded = false
                                    when (dropItem.id) {
                                        1 -> { /* 发送编辑动态意图 */
                                            onClickEditDynamic(userId)
                                        }
                                        2 -> { /* 发送跳转话题页面意图 */
                                            onClickSubject(userId)
                                        }
                                        else -> {
                                            Unit
                                        }
                                    }

                                }
                            )
                        }
                    }
                }
            }
        )
        /* 动态内容视图 */
        // 交错网格布局
        LazyVerticalStaggeredGrid(
            StaggeredGridCells.Fixed(2),
            verticalItemSpacing = 4.dp,
            horizontalArrangement = Arrangement.spacedBy(4.dp),
            state = listState,
            content = {
                // 显示动态卡片
                items(dynamicDataList) { dynamicData ->
                    DynamicItem(
                        dynamicData = dynamicData,
                        lookDynamicInfoClickListener = object : LookDynamicInfoClickListener {
                            override fun onLookDynamicInfoClicked(dynamicId: Int, authorId: Int) {
                                onClickDynamicInfo(dynamicId, authorId)
                            }
                        }
                    )
                }
            },
            modifier = Modifier.fillMaxSize()
        )
    }
}

/**
 * 查看动态信息
 */
interface LookDynamicInfoClickListener {
    fun onLookDynamicInfoClicked(dynamicId: Int, authorId: Int)
}



/**
 * 动态item：显示动态的内容
 */
@Composable
fun DynamicItem(
    dynamicData: DynamicData,
    lookDynamicInfoClickListener: LookDynamicInfoClickListener
) {
    var isExpanded by remember { mutableStateOf(false) }

    val coroutineScope = rememberCoroutineScope()
    var createDate: String = ""

    coroutineScope.launch {
        dynamicData.gmtCreate.let { it->
            createDate = it.let { it1 -> DateUtils.dateToStr(it1) }.toString()
        }
    }

    /* 动态Item的整体 */
    Surface(
        modifier = Modifier
            .padding(4.dp)
            .fillMaxWidth()
            .wrapContentHeight()
    ) {
        Column {
            Spacer(
                modifier = Modifier
                    .width(10.dp)
                    .wrapContentHeight()
            )
            /* 第一行：图片，自适应高度，圆角 */
            AsyncImage(
                model = dynamicData.dynamicImage?.image,
                contentDescription = null,
                modifier = Modifier
                    .shadow(elevation = 5.dp, shape = MaterialTheme.shapes.medium)
                    .fillMaxWidth()
                    .wrapContentHeight()
                    .clickable {/* 处理点击事件：跳转动态信息页面 */
                        lookDynamicInfoClickListener.onLookDynamicInfoClicked(
                            dynamicId = dynamicData.id,
                            authorId = dynamicData.uid
                        )
                    },
                contentScale = ContentScale.Crop
            )
            /* 第二行：文本内容 */
            Row(
                modifier = Modifier
                    .padding(5.dp)
                    .clickable { isExpanded = !isExpanded }
            ) {
                Text(text = dynamicData.content, maxLines = if (isExpanded) Int.MAX_VALUE else 2)
            }
            /* 第三行：用户卡片 */
            Row(
                modifier = Modifier
                    .padding(all = 5.dp)
                    .fillMaxWidth(),
                horizontalArrangement = Arrangement.Start,//设置水平居左对齐
                verticalAlignment = Alignment.CenterVertically//设置垂直居中对齐
            ) {
                /* 用户头像 和 用户名 */
                Row(
                    modifier = Modifier.wrapContentWidth()
                ) {
                    Image(
                        painter = painterResource(R.drawable.ab1_inversions),
                        contentDescription = null,
                        contentScale = ContentScale.Crop,
                        modifier = Modifier
                            .size(45.dp)
                            .clip(CircleShape)
                            .border(1.dp, MaterialTheme.colorScheme.primary, CircleShape)
                    )
                    Spacer(
                        modifier = Modifier
                            .width(5.dp)
                            .wrapContentHeight()
                    )
                    Column {
                        Text(
                            text = "username",
                            color = MaterialTheme.colorScheme.secondary,
                            style = MaterialTheme.typography.titleSmall
                        )
                        Spacer(
                            modifier = Modifier
                                .height(5.dp)
                                .wrapContentWidth()
                        )
                        Row(
                            verticalAlignment = Alignment.CenterVertically//设置垂直居中对齐
                        ) {
                            Text(
                                text = "发布于 ${createDate}",
                                color = MaterialTheme.colorScheme.secondary,
                                style = MaterialTheme.typography.titleSmall
                            )
                        }
                    }
                }
                /* 点赞控件 */
//                Row(
//                    modifier = Modifier.fillMaxWidth(),
//                    horizontalArrangement = Arrangement.End,//设置水平居右对齐
//                ) {
//                    LikeDynamic()
//                }
            }
        }
    }


}


/**
 * 点赞控件
 */
@Composable
fun LikeDynamic() {
    var isLike by remember { mutableStateOf(false) }
    var likedNum by remember { mutableStateOf(0) }

    Row(
        horizontalArrangement = Arrangement.Center,//设置水平居中对齐
        verticalAlignment = Alignment.CenterVertically//设置垂直居中对齐
    ) {
        /* 点赞数量 */
        Text(
            text = "赞 $likedNum",
            color = MaterialTheme.colorScheme.secondary,
            style = MaterialTheme.typography.titleSmall
        )
        Spacer(
            modifier = Modifier
                .width(5.dp)
                .wrapContentHeight()
        )
        /* 点赞控件 */
        IconButton(onClick = {
            /*TODO：处理点赞意图的回调 */
            isLike = !isLike
            if (isLike) {
                likedNum += 1
            } else {
                likedNum -= 1
            }
        }) {
            /* 使用条件判断，如果当前用户已点赞则填充颜色，否则不填充 */
            Image(
                painter = if (isLike) painterResource(R.drawable.ic_good_true) else painterResource(
                    R.drawable.ic_good
                ),
                contentDescription = null
            )
        }
    }
}
